"""
FileName：callback_verifier.py
Description：
Author：gaojiahui
Time：2025/8/16 15:41
Website：https://gitee.com/gao-jiahui
"""
import hashlib
import hmac

from flask import request, jsonify

from day03_mock.flask_for_mock_pay import app

"""回调验证工具"""

class CallbackVerifier:
    def __init__(self,secret_key):
        self.secret_key = secret_key.encode()

    def generate_signature(self,data):
        """生成回调签名"""
        sorted_data = sorted(data.items())
        query_str = "&".join([f"{k}={v}" for k,v in sorted_data if k != "sign"])
        return hmac.new(self.secret_key,query_str.encode(),hashlib.sha256).hexdigest()

    def verify_callback(self,callback_data):
        """验证回调签名"""
        received_sign = callback_data.get("sign")
        if not received_sign:
            return False

        expected_sign = self.generate_signature(callback_data)
        return hmac.compare_digest(received_sign,expected_sign)

# 在Mock服务中使用
@app.route('/mock-pay/callback',methods=['POST'])
def handle_callback():
    verifier = CallbackVerifier(secret_key="pig_payment_secret")
    callback_data = request.json

    if not verifier.verify_callback(callback_data):
        return jsonify({"code": 403,"msg": "签名验证失败"}),403
    # 处理有效回调。。。